var app = getApp();
const apiHost = require('../../../../../common/api_host.js');
var utils = require('../../../../../utils/utils.js');
var httpJson=require('../../../../../utils/http_json.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    /***默认为true */
    chooseToday:true,
   pageNum:0,
    pageSize:10,
    choosedDay:0,
    todayPageNum:0,pastPageNum:0,
   
    
   

  },
  //触底时触发
  scrolltolower :function(){
    console.log('触底了')
    /**判断当前是否加载完毕 */
    //选择了今日
    if(this.data.chooseToday){

        if(this.data.todayList.length<this.data.todayTotalCount){
           this.setData({
            todayhasMore:true
           })
         
          let pageNum=++this.data.todayPageNum
           this.getTodayList(pageNum)
        }

    }
    //选择了往日
    if(!this.data.chooseToday){

      if(this.data.pastList.length<this.data.pastTotalCount){
        this.setData({
          pasthasMore:true
        })
        let pageNum=++this.data.pastPageNum
        this.getPastLIst(0)
      }
      

   }
    
 },
 ToUpper :function(){
   
  // wx.getStorageSync("roomId",);
  // wx.getStorageSync("name",);
  //刷新今日脑洞列表
  // if(this.data.chooseToday){
  //   this.setData({
  //     todayPageNum:0,
  //   })
  //   this.getTodayTheme()
  // }
  // //刷新往日脑洞列表
  // else if(!this.data.chooseToday){
  //   this.setData({
  //     pastPageNum:0
  //   })
  //   this.getPastLIst(0)
  // }
  
  // wx.showLoading({

  //   title: '正在刷新',
  // })
  

},
  toDetail:function(e){
    //点击区域时转发的话就不跳转到详情页面
   
    if(e.target.dataset.reply==1){
      return;
    }
    let id=app.E(e,'myid')
    wx.navigateTo({
      url:"/pages/index/room/detail/detail?nd=1&id="+id
    })

  },
  todayOrBefore:function(e){
    if(e.currentTarget.dataset.myid==1){
      this.setData({
        chooseToday:true
      })
      
    }else if(e.currentTarget.dataset.myid==2){
      if(!this.data.pastList){
         this.getPastBrain()
        this.getPastId("",1)
      }
     
      this.setData({
        chooseToday:false
      })
    }
  },
  today_add_talk:function(e){
    wx.navigateTo({
      url: '../../../room/add/add?myid=1&theme='+this.data.theme.name+'&themeId='+this.data.theme.id
    })

  },
  getTodayTheme:function(){
    var  url=`${apiHost.config.portalApiHost}/portal/braintheme/todayBrain`;
    
    httpJson.get(url,{},res=>{
      if(res.data.errorCode==1){
        wx.hideLoading();
        this.setData({
          todayNoContent:true
        })
      }
      if(res.data.errorCode!=0){
        wx.hideLoading()
        utils.errToast(res.data.msg,1000)
      }
      if(res.data.errorCode==0){
        setTimeout(()=>{
          wx.hideLoading()
          wx.stopPullDownRefresh()
        },1000)
        this.setData({
          theme:res.data.body
        
        })
        this.getTodayList(0)
      }
    })
  },
  getTodayList:function(pageNum){
    var  url=`${apiHost.config.portalApiHost}/portal/braintheme/content`;
    let data={
      pageNum,pageSize:10,themeId:this.data.theme.id
    }
    httpJson.get(url,data,res=>{
     
      if(res.data.errorCode!=0){
        wx.hideLoading()
        utils.errToast(res.data.msg,1000)
      }
      
      if(res.data.errorCode==0){
        wx.hideLoading()

        if(pageNum==0){
          this.data.todayList=res.data.body.rows
        }
        /**判断是否还有数据 */
        if(res.data.body.totalPage==this.data.todayPageNum+1){
          this.setData({
            todayhasMore:false
          })

        }
        /**此时进行分页处理 */
        if(data.pageNum>0){
          this.data.todayList= this.data.todayList.concat(res.data.body.rows);
        }

        if(res.data.body.rows.length==0){
          this.setData({
            todayNoContent:true
          })
          return;
        }
        res.data.body.rows.forEach((ele)=>{
          console.log("ele",ele)
          ele.time=utils.formatDate2(ele.createdTime)
        })
       
       
        this.setData({
          todayList:this.data.todayList,
          todayTotalCount:res.data.body.totalCount

        
        })
      }
    })
  },
  // 顶部显示时间的
  getPastBrain:function(){
    var date=new Date()
   let  today=date.getTime()
    console.log('!~!~!~~',today)
    var pastDate=[];
    var showDate=[];
    for(let i=1;i<11;i++){
      console.log(typeof pastDate[i])
      let oneDay=86400000;

      pastDate.push(utils.formatDate3(today-oneDay*i));
      showDate.push(utils.formatDateMD(today-oneDay*i));
    }
 
    this.setData({
      pastDate,
      showDate
    })


  },
  // 通过时间拿到id
  getPastId:function(e,index){
    wx.showLoading({title:'正在加载'})
    /**清空之前选过的数据 */
    this.setData({
      pastList:[],
      pastNoContent:false,
      pastMsg:""
    })
    console.log('index!~',index)
    
    if(e){
      console.log('1e!!!!',e)
      var idx=app.E(e,'idx');
      this.setData({
        choosedDay:idx
      })
    }
  
    var  url=`${apiHost.config.portalApiHost}/portal/braintheme/pastBrain`;
   
    // 第一次加载时默认显示最近一天
    if(index){
     var  data={
            publishTime:this.data.pastDate[0],
          }
          console.log('data!@!',data)
    }
    // 点击时获取到index
    if(!index){
      var data={
        publishTime:this.data.pastDate[idx],
      }
    }
    httpJson.get(url,data,res=>{
      if(res.data.errorCode==1){
        wx.hideLoading()
        utils.errToast(res.data.msg,1000)
        this.setData({
          pastNoContent:true
        })
        return;
      
      }
      if(res.data.errorCode!=0){
        wx.hideLoading()
        utils.errToast(res.data.msg,1000)
      }
      if(res.data.errorCode==0){

      //  显示主题
        this.setData({
          pastMsg:res.data.body,
          pastThemeId:res.data.body.id
        
        })
        // let params={pageNum:0,themeId:res.data.body.id}
        this.getPastLIst(0)
       
      }
    })
    

  },
  getPastLIst:function(pageNum){
    var  url=`${apiHost.config.portalApiHost}/portal/braintheme/content`;
    let data={
      pageNum,pageSize:10,themeId:this.data.pastThemeId
    }
    
    httpJson.get(url,data,res=>{
      if(res.data.errorCode!=0){
        wx.hideLoading()
        utils.errToast(res.data.msg,1000)
      }
      
      if(res.data.errorCode==0){
        setTimeout(()=>{
          wx.hideLoading()
          wx.stopPullDownRefresh()
        },1000)

        /**start1套路代码 */
            if(pageNum==0){
              this.data.pastList=res.data.body.rows
            }
            /**判断是否还有数据 */
            if(res.data.body.totalPage==this.data.pastPageNum+1){
              this.setData({
                pasthasMore:false
              })
            }
            /**此时进行分页处理 */
            if(data.pageNum>0){
              this.data.pastList= this.data.pastList.concat(res.data.body.rows);
            }
        /**end1套路代码 */


        if(res.data.body.rows.length==0){
          this.setData({
            pastNoContent:true
          })
          return;
        }
        res.data.body.rows.forEach((ele)=>{
         
          ele.time=utils.formatDate2(ele.createdTime)
        })
        this.setData({
          pastList:this.data.pastList,
          pastTotalCount:res.data.body.totalCount
         
        
        })
       
      }
    })
  },
  addLikeContent:function(e){
   
    let contentId=app.E(e,"myid");
    let userLike=app.E(e,'islike');
    let index=app.E(e,'idx');
    
    console.log(contentId,userLike,index)
    var  url;
    if(userLike){
      url =`${apiHost.config.portalApiHost}/portal/content/removeLike`;
      let data={contentId}
      httpJson.post(url,data,res=>{
        if(res.data.errorCode==0){
          var params={};
          if(e.currentTarget.dataset.today){
            var str=`todayList[${index}].userLike`;

            this.data.todayList[index].likeNum--
            this.setData({
              todayList:this.data.todayList
            })
          }else{
            var str=`pastList[${index}].userLike`;

            this.data.pastList[index].likeNum--
            this.setData({
              pastList:this.data.pastList
            })
          }
          
          params[str]=false;
          this.setData(params)
        }
      })
    }
    if(!userLike){
      url =`${apiHost.config.portalApiHost}/portal/content/addLike`;
      let data={contentId}
      httpJson.post(url,data,res=>{
        if(res.data.errorCode==0){
          var params={};
          if(e.currentTarget.dataset.today){
            var str=`todayList[${index}].userLike`;

            this.data.todayList[index].likeNum++
            this.setData({
              todayList:this.data.todayList
            })

          }else{
            var str=`pastList[${index}].userLike`;

            this.data.pastList[index].likeNum++
            this.setData({
              pastList:this.data.pastList
            })

          }
          params[str]=true;
        this.setData(params)
        }
      })
    }
  },
  formSubmit: function(e) {


    var formId = e.detail.formId;
  
    let path = `${apiHost.config.portalApiHost}/portal/userformId/add`;
    httpJson.post(path, { 'formId': formId}, function (data) {
      let res = data.data;
     
    })
   
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
    app.verifyLogin()
    wx.showLoading({
      title: '加载中',
    })
    // this.getTodayTheme()
   


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTodayTheme()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
 //刷新今日脑洞列表
 if(this.data.chooseToday){
  this.setData({
    todayPageNum:0,
  })
  this.getTodayTheme()
  
wx.showLoading({

  title: '正在刷新',
})
}
//刷新往日脑洞列表
else if(!this.data.chooseToday){
  setTimeout(()=>{
    wx.hideLoading()
    wx.stopPullDownRefresh()
  },1000)
  // this.setData({
  //   pastPageNum:0
  // })
  // this.getPastLIst(0)
}

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  
  onShareAppMessage(res) {
    app.share()
    if (res.from === 'button') {
      var content=res.target.dataset.content
     
      if(content.length>50){
        content=content.substr(0,50)+'...'
      }
      var title=content
    }
    if(res.from === 'menu'){
      var imageUrl="/images/index/reply/reply.png";
      var title='我正在惊人院，邀请你来……'
    }
    return {
      title,
      imageUrl
      
    }
  }
})